package cz.mendelu.swi2.skladDilu.controllers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cz.mendelu.swi2.skladDilu.Forms.FEditForm;
import cz.mendelu.swi2.skladDilu.Part;
import cz.mendelu.swi2.skladDilu.Warehouse;


@Controller
@RequestMapping("/skladdilu/editpart")
public class CEditPartController {

	@Autowired   
	private Warehouse warehouse;
	
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView showForm(HttpServletRequest request, HttpServletResponse response) {
		
		 ModelAndView mview = new ModelAndView("editPart") ;
		@SuppressWarnings("unchecked")
		Map<String, String[]> parameters = request.getParameterMap();
		for(String parameter : parameters.keySet()) {
		    if(parameter.toLowerCase().startsWith("idpart")) {
		        String[] values = parameters.get(parameter);
		        Long uid = Long.valueOf(values[0]);
		        Part editovany = warehouse.getPart(uid);
		        if(editovany!=null)
		        	mview.addObject("editItem", editovany) ;
		        else
		         return new ModelAndView("skladDilu"); 
			       
		    }
		}
		 return mview;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView processForm(@Valid FEditForm editForm, BindingResult result) {
		 ModelAndView mview =null;
		if (result.hasErrors()) {
			
			mview= new ModelAndView("editPart") ;
			mview.addObject("message","Chyba ve vstupnich datech");
			mview.addObject("editItem",warehouse.getPart(editForm.getHuid()));
			mview.addObject("error",true);
			System.err.println("chyba v datech pri deditaci...");
			return mview;
		} 
		else{
		Part edit = warehouse.getPart(editForm.getHuid());
	      edit.setCount(editForm.getCount());
	      edit.setDetails(editForm.getDetails());
	      edit.setUid(editForm.getUid());
	      edit.setName(editForm.getName());
	        mview = new ModelAndView("skladDilu") ;
	        mview.addObject("listDilu", warehouse.getListOfParts()) ;
	        mview.addObject("inventura",false);
		  return mview;
		}
	}


  }
